package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantSysConfig;
import cn.yuanqiao.archive.appManager.mapper.TenantSysConfigMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.common.constant.CacheConstants;
import cn.yuanqiao.common.core.text.Convert;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.service.RedisService;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zjj
 * @date 2023/6/28
 */
@Service
public class TenantSysConfigServiceImpl implements ITenantSysConfigService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private TenantSysConfigMapper configMapper;
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        TenantSysConfig config = new TenantSysConfig();
        config.setConfigKey(configKey);
        config.setTenantCode(SecurityUtils.getLoginUser().getUser().getTenantCode());
        TenantSysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String selectConfigByCode(String configKey, String code) {
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKeyByCode(configKey,code)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        TenantSysConfig config = new TenantSysConfig();
        config.setConfigKey(configKey);
        config.setTenantCode(code);
        TenantSysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            redisService.setCacheObject(getCacheKeyByCode(configKey,code), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    private String getCacheKeyByCode(String configKey, String code) {
        return code+"_"+CacheConstants.SYS_CONFIG_KEY + configKey;

    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return SecurityUtils.getTenantCode()+"_"+CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
